home *** CD-ROM | disk | FTP | other *** search
/ Megaware 1 / Megaware Volume 1.iso / programg / c-tutor / answers / ch05_3.cpp < prev    next >
C/C++ Source or Header  |  1990-07-20  |  2KB  |  89 lines

  1.                              // Chapter 5 - Programming exercise 3
  2. #include "iostream.h"
  3.  
  4. class rectangle {              // A simple class
  5.    int height;
  6.    int width;
  7. public:
  8.    rectangle(void);            // with a constuctor
  9.    int area(void);             // two methods
  10.    void initialize(int, int);
  11.    ~rectangle(void);           // and a destructor
  12. };
  13.  
  14. rectangle::rectangle(void)     // constuctor
  15. {
  16.    cout << "Rectangle constructor speaking\n";
  17.    height = 6;
  18.    width = 6;
  19. }
  20.  
  21. int rectangle::area(void)      //Area of a rectangle
  22. {
  23.    return height * width;
  24. }
  25.  
  26. void rectangle::initialize(int init_height, int init_width)
  27. {
  28.    height = init_height;
  29.    width = init_width;
  30. }
  31.  
  32. rectangle::~rectangle(void)    // destructor
  33. {
  34.    cout << "Rectangle destructor speaking\n";
  35.    height = 0;
  36.    width = 0;
  37. }
  38.  
  39. struct pole {
  40.    int length;
  41.    int depth;
  42. };
  43.  
  44.  
  45.  
  46. main()
  47. {
  48. rectangle box, square;
  49. pole flag_pole;
  50.  
  51.    cout << "The area of the box is " << 
  52.                        box.area() << "\n";
  53.    cout << "The area of the square is " << 
  54.                        square.area() << "\n";
  55.  
  56. // box.height = 12;
  57. // box.width = 10;
  58. // square.height = square.width = 8;
  59.  
  60.    box.initialize(12, 10);
  61.    square.initialize(8, 8);
  62.  
  63.    flag_pole.length = 50;
  64.    flag_pole.depth = 6;
  65.  
  66.    cout << "The area of the box is " << 
  67.                        box.area() << "\n";
  68.    cout << "The area of the square is " << 
  69.                        square.area() << "\n";
  70. // cout << "The funny area is " << 
  71. //                     area(square.height, box.width) << "\n";
  72. // cout << "The bad area is " << 
  73. //                     area(square.height, flag_pole.depth) << "\n";
  74. }
  75.  
  76.  
  77.  
  78.  
  79. // Result of execution
  80. //
  81. // Rectangle constructor speaking
  82. // Rectangle constructor speaking
  83. // The area of the box is 36
  84. // The area of the square is 36
  85. // The area of the box is 120
  86. // The area of the square is 64
  87. // Rectangle destructor speaking
  88. // Rectangle destructor speaking
  89.